/**
 * @author {Yuntao Zhou}
 */
/* Add Windows panel 
 * @param {Object} containerEl
 */
var QS_WorkspaceToolbar_WindowsItem=function(obj,containerEl){
	this.toolbar=obj;
	this.containerEl=containerEl;
	this.maskEl=$('<div id="wstb-mask"></div>').appendTo($('body'));
	this.el=null;
	this.tabMenu=null;
	this.tabMenuContainerEl=null;
	this.menuSelectIndex=null;
	this.menuIndexs=[];
	this.activeComponentName=null;
	this.activeComponentSubType=null;
	this.contentScrollPN=null; 
	this.centerX=null;
	this.centerY=null;
	this.isAddComponent = null;
	this.isStartDrag=false;
	var qslang=QS_Lang.workspace;
	this.hiddenInput=["0","11","12","13","14","15","16","18","19","21","22","23","30"];  // change by Jacye, remove the "1" to show the autocomplete in chart preset widow.
	this.showInput=["14_8","14_9"]; //sub type
	this.componentList=null;
	this.html =	'<div class="rtq-wstb-content rtq-wstb-windowsItem">'+
					'<div class="rtq-wstb-translucent"></div>'+//add a div for translucent layout, edited by wind @ 20120210
				  	'<div class="hd">'+
						'<div class="title"><h3>'+qslang["tb_title"]+'</h3></div>'+
						'<div class="operator">[X]  '+qslang["tb_close"]+'</div>'+
					'</div>'+
					'<div class="bd">'+
						'<div class="leftMenu">'+
							'<ul>'+
								'<li index="0" catkey="'+qslang["tb_essential"]+'">'+qslang["tb_essential"]+'</li>'+		
							'</ul>'+
						'</div>'+
						'<div class="content">'+
							'<div class="wstb-tabmenu"></div>'+
							'<div class="data">'+
								'<div class="component-list" catkey="'+qslang["tb_essential"]+'">'+
									'<ul></ul>'+
								'</div>'+
								'<div class="component-hover">'+
									'<div class="autocp-container">'+
										'<div class="autocp">'+
											'<input id="autocpipt_wstb" class="qs-ui-ipt" type="text"/>'+
											'<div class="input-clear"></div>'+
											'<div id="autocpddl_wstb" class="autocp_ddl"></div>'+
										'</div>'+
									'</div>'+
									'<div class="msg">'+qslang["tb_d&d"]+'</div>'+
								'</div>'+
							'</div>'+
						'</div>'+
					'</div>'+					
				'</div>';
	this.imgUrl = '//rtqimg.morningstar.com/';
	this.init();	
};
QS_WorkspaceToolbar_WindowsItem.prototype = {
	init: function(){
		this.el = $(this.html).appendTo(this.containerEl),qslang=QS_Lang.workspace;
		this.tabMenuEl=this.el.find('.wstb-tabmenu');
		this.newsConfig = {
			"briefinginplay": {title: qslang["tb_newwiew_binplay"],model: 'BRIEFING_INPLAY',symbolType:'all',plusSymbol:false},
			"briefingtrader": {title: qslang["tb_newview_btrader"],model: 'BRIEFING_TRADER',symbolType:'all',plusSymbol:false},
			"samestoresales":{title: qslang["tb_newview_sss"],model: 'SAME_STORE_SALES',symbolType:'all'},
			"markets":{title: qslang["tb_newview_market"],currentViewID: '-11',type:'market'},
			"stock":{title: qslang["tb_newview_stocknews"],currentViewID: '-12',type:'stock'}
		};
		this.tabData={
			'0':{
				show:false
			},
			'1':{
				show:false
			},
			'2':{
				show:true,
				categoryKey:qslang["tb_research"],
				data:[{
					txt:qslang["tb_research_stock"],
					val:'ST',
					closable:false
				},{
					txt:qslang["tb_research_prestock"],
					val:'PR',
					closable:false
				},{
					txt:qslang["tb_research_efund"],
					val:'FE',
					closable:false
				},{
					txt:qslang["tb_research_mfund"],
					val:'FO',
					closable:false
				},{
					txt:qslang["tb_research_cfund"],
					val:'FC',
					closable:false
				}]
			},
			'3':{
				show:false
			},
			'4':{
				show:false
			},
			'5':{
				show:false
			}
		};	
		//Research>Quick take>Quote>Chart>News>Options>Time and Sales>Market Depth >Watchlist>Forex>Calendars>Commodity
		var essentialComponentlist=[{
				"type":9,
				"value": "9",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_sr.png",
				"info":qslang["tb_eview_research"]
			},
			{
				"type":3,
				"value": "3",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_qt.png",
				"info":qslang["tb_eview_qt"]
			},
			{
				"type":10,
				"value": "10",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_quote.png",
				"info":qslang["tb_eview_quote"]
			},
			{
				"type":1,
				"value": "1",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_chart.png",
				"info":qslang["tb_eview_chart"]
			},
			{
				"type":2,
				"value": "2",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_news.png",
				"info":qslang["tb_eview_news"]
			},
			{
				"type":8,
				"value": "8",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_options.png",
				"info":qslang["tb_eview_options"]
			},
			{
				"type":7,
				"value": "7",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_ts.png",
				"info":qslang["tb_eview_t&s"]
			},
			{
				"type":6,
				"value": "6",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_l2.png",
				"info":qslang["tb_eview_market"]
			},
			{
				"type":0,
				"value": "0",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_watchlist.png",
				"info":qslang["tb_eview_wl"]
			},
			{
				"type":11,
				"value": "11",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_forex.png",
				"info":qslang["tb_eview_forex"]
			},{
				"type":12,
				"value": "12",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_calendars.png",
				"info":qslang["tb_eview_calendars"]
			},{
				"type":13,
				"value": "13",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_commodity.png",
				"info":qslang["tb_eview_futures"]
			},{
				"type":16,
				"value": "16",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_crt.png",
				"info":qslang["tb_eview_crossrates"]
			},{
				"type":27,
				"value": "27",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_historical_price.png",
				"info":qslang["tb_eview_price"]

			}/*,{
				"type":0,
				"value": "0",
				"subType":"0_5",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_watchlist.png",
				"info":qslang["tb_eview_wlforex"]

			}*/];

		var watchlistComponentList=	[{
			"type":0,
			"value": "0",
			"imgPosition":"0 0",
			"imgSrc":"bg_pre_watchlist.png",
			"info":qslang["tb_wlview_wl"]
		},{
			"type":0,
			"value": "0",
			"subType":"0_1",
			"imgPosition":"0 0",
			"imgSrc":"bg_pre_wt_wrap.png",
			"info":qslang["tb_wlview_wrap"]
		},{
			"type":0,
			"value": "0",
			"subType":"0_2",
			"imgPosition":"0 0",
			"imgSrc":"bg_pre_wt_group.png",
			"info":qslang["tb_wlview_group"]
		},{
			"type":0,
			"value": "0",
			"subType":"0_3",
			"imgPosition":"0 0",
			"imgSrc":"bg_pre_wt_gw.png",
			"info":qslang["tb_wlview_g&w"]
		},{
			"type":0,
			"value": "0",
			"subType":"0_4",
			"imgPosition":"0 0",
			"imgSrc":"bg_pre_wt_heatmap.png",
			"info":qslang["tb_wlview_heatmap"]
		}];
		var chartComponentList=[{
				"type":1,
				"value": "1",
				"subType":"1_1",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_chart_intraday.png",
				"info":qslang["tb_cview_intraday"]
			},{
				"type":1,
				"value": "1",
				"subType":"1_2",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_chart_ohlc.png",
				"info":qslang["tb_cview_iohlc"]
			},{
				"type":1,
				"value": "1",
				"subType":"1_3",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_chart_3yr.png",
				"info":qslang["tb_cview_3yr"]
			},{
				"type":1,
				"value": "1",
				"subType":"1_4",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_chart_3yr_ohlc.png",
				"info":qslang["tb_cview_3ohlc"]
			},{
				"type":1,
				"value": "1",
				"subType":"1_5",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_chart_cvs.png",
				"info":qslang["tb_cview_c.sp"]
			},{
				"type":1,
				"value": "1",
				"subType":"1_6",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_chart_ma.png",
				"info":qslang["tb_cview_ma"]
			},{
				"type":1,
				"value": "1",
				"subType":"1_7",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_chart_price_indicators.png",
				"info":qslang["tb_cview_pind"]
			},{
				"type":1,
				"value": "1",
				"subType":"1_8",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_chart_volume_indicators.png",
				"info":qslang["tb_cview_vind"]
			},{
				"type":1,
				"value": "1",
				"subType":"1_9",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_chart_oscillator_indicators.png",
				"info":qslang["tb_cview_oind"]
			},{
				"type":1,
				"value": "1",
				"subType":"1_10",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_chart_fundamental.png",
				"info":qslang["tb_cview_fund"]
			},{
				"type":1,
				"value": "1",
				"subType":"1_11",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_chart_valuation.png",
				"info":qslang["tb_cview_valua"]
			},{
				"type":1,
				"value": "1",
				"subType":"1_12",
				"imgPosition":"0 0",
				"imgSrc":"bg_pre_chart_forex_chart.png",
				"info":qslang["tb_cview_forex"]
			}];
		var newsComponentList=[{
			"type":2,
			"value": "2",
			"subType":"2_1",
			"imgPosition":"0 0",
			"imgSrc":"bg_pre_news.png",
			"info":qslang["tb_newview_news"]
		},{
			"type":2,
			"value": "2",
			"subType":"2_2",
			"imgPosition":"0 0",
            "imgSrc":"bg_pre_news.png",
			"info":qslang["tb_newview_lnews"]
		},{
			"type":2.15,
			"value": "2",
			"subType":"briefinginplay",
			"imgPosition":"0 0",
            "imgSrc":"bg_pre_news.png",
			"info":qslang["tb_newview_binplay"]
		},{
			"type":2.16,
			"value": "2",
			"subType":"briefingtrader",
			"imgPosition":"0 0",
            "imgSrc":"bg_pre_news.png",
			"info":qslang["tb_newview_btrader"]
		},{
			"type":15,
			"value": "15",
			"imgPosition":"0 0",
            "imgSrc":"bg_pre_news2.png",
			"info":qslang["tb_newview_sss"]
		},{
            "type":22,
            "value": "22",
			"subType":"markets",
            "imgPosition":"0 0",
            "imgSrc":"bg_pre_news_marketsoverview.png",
            "info":qslang["tb_newview_market"]
        },{
            "type":22,
            "value": "22",
			"subType":"stock",
            "imgPosition":"0 0",
            "imgSrc":"bg_pre_news_stockoverview.png",
            "info":qslang["tb_newview_stocknews"]
        }];
		var marketComponentList=[{
			"type":14,
			"value": "14",
			"subType":"14_1",
			"imgPosition":"0 0",
			"imgSrc":"bg_pre_markets_indexes.png",
			"info":qslang["tb_mview_index"]
		},{
			"type":14,
			"value": "14",
			"subType":"14_2",
			"imgPosition":"0 0",
			"imgSrc":"bg_pre_markets_barometer.png",
			"info":qslang["tb_mview_barometer"]
		},{
            "type":19,
            "value": "19",
            "imgPosition":"0 0",
            "imgSrc":"bg_pre_markets_gainers.png",
            "info":qslang["tb_mview_gla"]
        },{
			"type":14,
			"value": "14",
			"subType":"14_4",
			"imgPosition":"0 0",
			"imgSrc":"bg_pre_markets_bond.png",
			"info":qslang["tb_mview_bond"]
		},{
			"type":14,
			"value": "14",
			"subType":"14_5",
			"imgPosition":"0 0",
			"imgSrc":"bg_pre_markets_sectors.png",
			"info":qslang["tb_mview_sector"]
		},{
			"type":14,
			"value": "14",
			"subType":"14_6",
			"imgPosition":"0 0",
			"imgSrc":"bg_pre_markets_cd.png",
			"info":qslang["tb_mview_futures"]
		},{
			"type":12,
			"value": "12",
			"subType":"14_7",
			"imgPosition":"0 0",
            "imgSrc":"bg_pre_calendars.png",
			"info":qslang["tb_mview_calendar"]
		},{
			"type":23,
			"value": "23",
			"subType":"",
			"imgPosition":"0 0",
			"imgSrc":"bg_pre_calendars_overview.png",
			"info":qslang["tb_mview_overview"]
		},{
			"type":14,
			"value": "14",
			"subType":"14_8",
			"imgPosition":"0 0",
			"imgSrc":"bg_pre_markets_volatility.png",
			"info":qslang["tb_mview_vola"]
		},
		{
			"type":14,
			"value": "14",
			"subType":"14_9",
			"imgPosition":"0 0",
			"imgSrc":"bg_pre_markets_sp.png",
			"info":qslang["tb_mview_s&p"]
		},{
			"type":14,
			"value": "14",
			"subType":"14_10",
			"imgPosition":"0 0",
			"imgSrc":"bg_pre_markets_usindex.png",
			"info":qslang["tb_mview_wlindex"]
		},{
			"type":14,
			"value": "14",
			"subType":"14_11",
			"imgPosition":"0 0",
			"imgSrc":"bg_pre_markets_dow.png",
			"info":qslang["tb_mview_heatmap"]
		},{
            "type":18,
            "value": "18",
            "imgPosition":"0 0",
            "imgSrc":"bg_pre_markets_activity.png",
            "info":qslang["tb_mview_exch"]
        },{
			"type":21,
			"value": "21",
			"imgPosition":"0 0",
			"imgSrc":"bg_pre_sectors.png",
			"info":qslang["tb_mview_screener"]
		},{
			"type":30,
			"value": "30",
			"imgPosition":"0 0",
			"imgSrc":"bg_pre_fairvalue.png",
			"info":qslang["tb_mview_fairvalue"]
		}];
		this.menuSelectIndex=(typeof Terminal.getConfig('HideToolbarMenuIndex')!='undefined')?Terminal.getConfig('HideToolbarMenuIndex'):"0";
		this._addDom(essentialComponentlist,this.el.find('div[catkey="'+qslang["tb_essential"]+'"] ul'),0);
		if(QSPC.checkPermission(0)){
			this._addGroupDom(watchlistComponentList,qslang["tb_wl"],1);
		}
		if(QSPC.checkPermission(1)){
			this._addGroupDom(chartComponentList,qslang["tb_chart"],3);
		}
		if(QSPC.checkPermission(2)){
			this._addGroupDom(newsComponentList,qslang["tb_new"],4);
		}
		if(QSPC.checkPermission(9)){
			this._addTabGroupDom(2);
			//this._addGroupDom(srComponentList,qslang["tb_research"],2);
		}
		if(QSPC.checkPermission(14)){
			this._addGroupDom(marketComponentList,qslang["tb_market"],5);
		}
		
		if($.inArray(this.menuSelectIndex,this.menuIndexs)<= -1){
			this.menuSelectIndex=0;
		}	
		this._initEvents();
		this._createTabMenu(this.tabMenuEl);
		this.contentScrollPN=new Util.ScrollPanel(this.el.find('.bd .content .data'));
	},
	_addTabGroupDom:function(index){
		var tabList=this.tabData[index].data;
		var cat=this.tabData[index].categoryKey;
		var menuSelectEl=$('<li index="'+index+'" catkey="'+cat+'">'+cat+'</li>').appendTo(this.el.find('.leftMenu ul'));
		if(tabList){
			for(var i=0,l=tabList.length;i<l;i++){
				this._addGroupDom(this._getComponentList(index,tabList[i].val),tabList[i].val,index);
			}
		}
	},
	_getComponentList:function(index,sType){
		var list=[{
			"type":9,
			"value": "9",
			"imgPosition":"0 0",
            "imgSrc":"bg_pre_sr.png",
			"info":QS_Lang.workspace["tb_research"]
		},{
			"type":3,
			"value": "3",
			"subType":"3",
			"imgPosition":"0 0",
			"imgSrc":"bg_pre_qt.png",
			"info":QS_Lang.workspace["tb_eview_qt"]
		}];
		
		/**,{
			"type":10,
			"value": "10",
			"imgPosition":"0 0",
            "imgSrc":"bg_pre_quote.png",
			"info":"Quote"
		}];
		*/
		for(var code in QS_QT_TabMapping){
			if (QS_SMC.checkSecurityModule(sType, parseFloat(code,10))) {
				list.push({
					type:code,
					value: code,//QS_QT_TabMapping[code].value,
					subType:code,
					imgPosition:QS_QT_TabMapping[code].imgPosition,
					imgSrc:QS_QT_TabMapping[code].imgSrc,
					info:QS_QT_TabMapping[code].txt
				});	
			}
		}
		return list;
	},
	_createTabMenu:function(container){
		var self=this;
		this.tabMenu= new Util.TabMenu(container,[],{
			onActive: function(tab){
				self._activeTab(tab);
				self.setPanelSize(null,217);
			}
		},{
            autoResize: false,
            tabsList:false,
			autoFixtoText: true,
            closeAction: 'hide',
            autoSlideToActiveTab: false
		});	
	},
	registerAutoComplete:function(){
		 GB_qsAutoCompleteBox.subscription("autocpipt_wstb",function(data){
		 	workspaceManager.toolbar.windowsItem.autoCPCallback(data);
		 },{needClear:true});
	},
	_addGroupDom:function(data,cat,index){
		if (this.tabData[index].show != true) {
			this.menuIndexs.push(index + '');
			var menuSelectEl=$('<li index="'+index+'" catkey="'+cat+'">'+cat+'</li>').appendTo(this.el.find('.leftMenu ul'));
		}
		var componentListEl=$('<div class="component-list" catkey="'+cat+'"><ul></ul></div>').appendTo(this.el.find('.data'));
		this._addDom(data,componentListEl.find('ul'),index);
	},
	_addDom:function(list,el,index){
		var html='',subType='';
		index=typeof index!='undefined'?index:"";
		for(var i=0;i<list.length;i++){
			if(QSPC.checkPermission(list[i].type)){
				subType=list[i].subType||'';
				//html += '<li><a href="#" value="' + list[i].value + '" subType="'+subType+'"><img class="wstb-backgroundimage" src="IM/blank.gif" style="width:97px;height:69px;background-repeat:no-repeat;background-position:'+list[i].imgPosition+';" value="' + list[i].value + '" subType="'+subType+'" index="'+index+'"/></a><div class="info" align="center"><strong>' + list[i].info + '</strong></div></li>'
				html += '<li><a href="#" value="' + list[i].value + '" subType="'+subType+'"><img class="wstb-backgroundimage" src="IM/blank.gif" style="width:97px;height:69px;background-repeat:no-repeat;background-image:url('+this.imgUrl+'theme/'+QS_Theme+'/'+list[i].imgSrc+');background-position:'+list[i].imgPosition+';" value="' + list[i].value + '" subType="'+subType+'" index="'+index+'"/></a><div class="info" align="center"><strong>' + list[i].info + '</strong></div></li>'	
			}
		}
		$(html).appendTo(el);
	},
	_isAllow:function(code){
		if(code==2.15){//if trader true ,inPlay false
			return !QSPC.checkPermission(2.16)&&QSPC.checkPermission(2.15);
		}else{
			return QSPC.checkPermission(code);
		}
	},
	_initEvents:function(){
		var self=this;
		var hoverEl = self.el.find('.component-hover');
		this.el.find('.leftMenu').bind('click',function(e){
			e.preventDefault();
			var targetEl=$(e.target);
			if(e.target.tagName.toLowerCase()=='li'){
				self._activeMenu(targetEl.attr('index'));
			}
		});
		this.el.find('.operator').bind('click',function(e){
			workspaceManager.toolbar.hideContentBar();
		});
		this.el.find('.content').bind('mouseover',function(e){
				var target=$(e.target);
				if (e.target.tagName.toLowerCase() == 'img') {	
					var pp =target.offset();
					var index=target.attr('index');
					var height=self.tabData[index].show?-28:0;
					hoverEl.show().css({
						left: pp.left-233,
						top:pp.top-93+height
					});
					if (!self.isStartDrag) {
						self.activeComponentName = target.attr('value');
						self.activeComponentSubType=target.attr('subType');
					}
					if ($.inArray(target.attr('value'),self.hiddenInput)!=-1 && $.inArray(target.attr('subtype'),self.showInput)==-1) {//in hiddenInput but not in showinput
						//console.log("1="+hoverEl.find('.autocp').css('display'));	
						hoverEl.find('.autocp').css({
							visibility: 'hidden'
						});				
						hoverEl.removeClass('showInput');
						GB_qsAutoCompleteBox.hideBox();
						//console.log("2="+hoverEl.find('.autocp').css('display'));
					}else{	
						hoverEl.find('.autocp').css({
							visibility: 'visible'
						});	
						hoverEl.addClass('showInput');
						GB_qsAutoCompleteBox.changeBoxPosition("autocpipt_wstb");
					}
					
				}
	    });	
		this.el.find('.component-hover').bind('mousedown',function(e){
			self.isAddComponent=false;
			self.isStartDrag=true;
			var targetEl=$(e.target);
			if(targetEl.hasClass('input-clear')){
				targetEl.removeClass('input-over');
				var inputEl=self.el.find('input');
				inputEl.val('').focus();
			}else if(e.target.tagName.toLowerCase()=='td'||e.target.tagName.toLowerCase()=='input'){
				self.isAddComponent=false;
			}else{
				self.isAddComponent=true;	
			}
		}).bind('mouseup',function(e){
			self.isStartDrag=false;
			if (self.isAddComponent) {
				var x=e.clientX,y=e.clientY+15;
				if(x>=self.centerX){
					x=self.centerX*2-x;
				}if(y>=self.centerY){
					y=self.centerY*2-y-15;
				}
				var iptVal=self.el.find('input').val();
				self._addComponent(iptVal,self.activeComponentName,self.activeComponentSubType,x,y);		
			}
		});
		this.el.bind('mouseout',function(e){
			var target=$(e.target);
			if(target.hasClass("component-list")){
				hoverEl.hide();
				GB_qsAutoCompleteBox.hideBox();
			}
		});
		this.el.find('.component-hover input').bind('mousedown',function(e){
            e.stopPropagation();
			self.isAddComponent=false;
			self.el.find('.input-clear').addClass('input-over');
        }).bind('mouseup',function(e){
			e.stopPropagation();
			$(this).select();
		}).bind('mousemove',function(e){
			e.stopPropagation();
			self.isAddComponent=false;
		});
		var drag = new Util.Dragable(this.el.find('.component-hover')[0], {
            onDragStart: function(e, proxy){ 
				self.maskEl.show();
				self.isAddComponent=false;
				if (self.activeComponentSubType == '') {
					proxy.html(self.el.find('a[value=' + self.activeComponentName + ']').html());
				}else{
					proxy.html(self.el.find('a[subType=' + self.activeComponentSubType + ']').html());
				}
            },
            onDragEnd: function(e){
				self.maskEl.hide();
				var iptVal=self.el.find('input').val();
				self._addComponent(iptVal,self.activeComponentName,self.activeComponentSubType,e.clientX,e.clientY-15);
				self.isStartDrag=false;	               
            }
        }, {
            autoProxy:true,
            customClass: 'rtq-commodity-dd-proxy',
			  delay:500
        });
		
		$(window).bind('resize',function(e){
			self.setPanelSize(null,245);
		});
	},
	_activeTab:function(tab){
		var catKey=tab.val;
		this.el.find('.bd .content div[catKey!="'+catKey+'"]').filter('.component-list').hide();
		this.el.find('.bd .content div[catKey="'+catKey+'"]').filter('.component-list').show();
		this.el.find('.component-hover').hide();
	},
	_activeMenu:function(index){	
		this.menuSelectIndex=index;	
		if(Terminal.getConfig('HideToolbarMenuIndex')!=this.menuSelectIndex){
			Terminal.setConfig({
				HideToolbarMenuIndex:index
			});
		}
		var activeMenuEl=this.el.find('.leftMenu li[index="'+index+'"]');
		activeMenuEl.parent().find('li').css("background","none");
		activeMenuEl.css("background","#646464");
		if(this.tabData[index].show===true){
			this.tabMenuEl.show();
			this.tabMenu.reBindData(this.tabData[index].data);
			//this._menuSelectbyCategory(this.el.find('.leftMenu li[index="'+index+'"]'));
		}else{
			this.tabMenuEl.hide();
			this._menuSelectbyCategory(activeMenuEl);
			this.setPanelSize(null,245);
		}
	},
	_menuSelectbyCategory:function(target){
		var catKey=target.attr("catkey");
		this.el.find('.bd .content div[catKey!="'+catKey+'"]').filter('.component-list').hide();
		this.el.find('.bd .content div[catKey="'+catKey+'"]').filter('.component-list').show();
		this.el.find('.component-hover').hide();
	},
	autoCPCallback:function(ticker){
		this._addComponent(ticker,this.activeComponentName,this.activeComponentSubType);
	},
	_addComponent:function(ticker,ty,subType,x,y){ 
		if (!WorkspaceTabs.currentTab)
            return;

		var profile = getDefaultProfileByType(ty);
		if(subType!=''){
			if(subType=='3'){ // quick take
				profile.widget.title='Quicktake';
			}else if(QS_QT_TabMapping.hasOwnProperty(subType)){
				profile.widget.tab=subType;
				profile.widget.showTab=false;
				profile.widget.title=QS_QT_TabMapping[subType];
			}else if (this.newsConfig.hasOwnProperty(subType)) {
				$.extend(true,profile.widget,this.newsConfig[subType]);
				profile.name=profile.widget.title;
				if(ticker != "" || ticker.length != 0){
					profile.widget.symbolType='single';
				}
			}else {
				profile = $.extend(true, {}, MstarData.PresetWindow[subType]);
			}
		}
        //add security type into profile - david
        if (this.tabMenu && this.tabMenu.currentTab) {
            if (profile.type == 1 || profile.type == 9 || profile.type == 3 || profile.type == 10) { //chart, research, quote, qt
                profile.widget.securityType = this.tabMenu.currentTab.id;
            }
        }
            
		if (ticker != "" || ticker.length != 0) {
			profile.widget.ticker = ticker;
			profile.widget.mTicker = ticker;
		}else if(typeof(profile.widget.ticker)=="undefined"&&typeof(profile.widget.mTicker)=="undefined"){
			profile.widget.ticker = "";
		}
		if(x){
			profile.x= x;
			profile.oldBox.left = x;
		}
		if(y){
			profile.y= y;
			profile.oldBox.top = y;
		}
        RtqDesktop.addModule(profile);
		this.el.find('.component-hover input').val('');
		this.el.find('.component-hover').hide();
	},
	addComponent:function(ticker,type,x,y){
		if (typeof x != 'undefined' && typeof y != 'undefined') {
			this._addComponent(ticker, type, '', x, y);
		}else{
			this._addComponent(ticker, type, '');
		}
	},
	setPanelSize:function(w, h){
        var parent = $(window);
		this.centerX=parseInt(parent.width()/2);
		this.centerY=parseInt(parent.height()/2);
        w = w||parent.width()-235;
        h = h||parent.height();
		this.el.find('.content').css('width',w);
        this.el.find('.bd .content .data').css({width:w, height:h});
        this.contentScrollPN.reSize(w,h);
    },
	show:function(){			
		this.el.show();
		//this._reSizeContent();
		this._activeMenu(this.menuSelectIndex);
		this._changeStyleByClass('.rtq-wstb-setting-btn', {
			background: '#ccc'
		});
	},
	hide:function(){	
		this.el.hide();
		this._changeStyleByClass('.rtq-wstb-setting-btn', {
			background: '#e4e4e4'
		});
	},
	_changeStyleByClass:function(cls,style){
		this.el.find(cls).css(style);
	}
};
/* Options panel 
 * @param {Object} containerEl
 */
var QS_WorkspaceToolbar_OptionsItem=function(obj,containerEl){
	this.toolbar=obj;
	this.containerEl=containerEl;
	this.el=null;
	this.contentHeadEl=null;
	this.contentScrollPN=null;
	var qslang=QS_Lang.workspace;
	this.html =	'<div class="rtq-wstb-content rtq-wstb-optionsItem">'+
					'<div class="rtq-wstb-translucent"></div>'+//add a div for translucent layout, edited by wind @ 20120210
					'<div class="hd">'+
						'<div class="title"><h3>'+qslang["tb_option_title"]+'</h3></div>'+
						'<div class="operator">[X]  '+qslang["tb_close"]+'</div>'+
					'</div>'+
					'<div class="bd">'+
						'<div class="leftMenu">'+
							'<ul>'+
								'<li index="0" catkey="grid">'+qslang["tb_option_grid"]+'</li>'+
								'<li index="1" catkey="Theme">'+qslang["tb_option_theme"]+'</li>'+
								//'<li index="2" catkey="workspace">Workspace</li>'+
								//'<li index="3" catkey="other">Other</li>'+
							'</ul>'+
						'</div>'+
						'<div class="content">'+
							'<div class="content-hd"></div>'+
							'<div class="data">'+
								'<div class="component-list" style="display:block;" catkey="grid"><ul></ul></div>'+
								'<div class="component-list" style="display:block;" catkey="Theme"><ul></ul></div>'+
								//'<div class="component-list" style="display:block;" catkey="workspace"></div>'+
				                //'<div class="component-list" style="display:block;" catkey="other"></div>'+
							'</div>'+
						'</div>'+
					'</div>'+					
				'</div>';
	this.init();
};
QS_WorkspaceToolbar_OptionsItem.prototype={
	init:function(){
		var qslang=QS_Lang.workspace;
		this.hdConfig = {
			'0': {
				show: true,
				description:qslang["tb_option_desc"]
			},
			'1': {
				show: false
			},
			'2': {
                show: false
            },
			'3': {
                show: false
            }
		};
		var gridList = [{
			"type":'grid',
			"value": 0,
			"imgPosition":"0 -69px",
			"imgSrc":"themes.png",
			"info":qslang["tb_option_gview_no"]
		},{
			"type":'grid',
			"value": 20,
			"imgPosition":"-97px -69px",
			"imgSrc":"themes.png",
			"info":qslang["tb_option_gview_vsma"]
		},{
            "type":'grid',
            "value": 40,
            "imgPosition":"-194px -69px",
			"imgSrc":"themes.png",
            "info":qslang["tb_option_gview_sma"]
        },{
            "type":'grid',
            "value": 60,
            "imgPosition":"-194px -69px",
			"imgSrc":"themes.png",
            "info":qslang["tb_option_gview_med"]
        },{
            "type":'grid',
            "value": 80,
            "imgPosition":"-291px -69px",
			"imgSrc":"themes.png",
            "info":qslang["tb_option_gview_lar"]
        },{
			"type":'grid',
			"value": 100,
			"imgPosition":"-388px -69px",
			"imgSrc":"themes.png",
			"info":qslang["tb_option_gview_vlar"]
		}];
		var themeList=[{
			"type":'theme',
			"value": "default",
			"imgPosition":"0 0",
			"imgSrc":"themes.png",
			"info":qslang["tb_option_tview_def"]
		},{
			"type":'theme',
			"value": "black",
			"imgPosition":"-194px 0",
			"imgSrc":"themes.png",
			"info":qslang["tb_option_tview_bak"]
		},{
			"type":'theme',
			"value": "gray",
			"imgPosition":"-97px 0",
			"imgSrc":"themes.png",
			"info":qslang["tb_option_tview_gray"]	
		}];
		this.el=$(this.html);
		this.timeout = null;
		this.el.appendTo(this.containerEl);
		this.contentHeadEl=this.el.find('.content .content-hd');
		this._initEvents();
		this.contentScrollPN=new Util.ScrollPanel(this.el.find('.bd .content .data'));
		this._addDom(gridList,this.el.find('div[catkey="grid"] ul'));
		this._addDom(themeList,this.el.find('div[catkey="Theme"] ul'));
		Util.addBetaTip(this.el.find('div[catkey="Theme"] ul strong').eq(1), this.el.find('div[catkey="Theme"] ul li').eq(1)); 
		Util.addBetaTip(this.el.find('div[catkey="Theme"] ul strong').eq(2), this.el.find('div[catkey="Theme"] ul li').eq(2)); 
	},
	_initEvents:function(){
		var self=this;
		this.el.find('.leftMenu').bind('click',function(e){
			e.preventDefault();
			var targetEl=$(e.target);
			if(e.target.tagName.toLowerCase()=='li'){
				self._activeMenu(targetEl.attr('index'));
			}
		});
		this.el.find('.operator').bind('click',function(e){
			self.hide();
		});
		this.el.find('.content').bind('click',function(e){
			var target=$(e.target);
			if (e.target.tagName.toLowerCase() == 'img'&&target.attr('type')=='theme') {	
				var value=target.attr('value');
				if(value==QS_Theme){
					return;
				}
				if(WorkspaceTabs.currentTab.id>0){
					workspaceManager.saveWorkspace(false,false,false,function(o){
						window.location='index.jsp?theme='+value;		
					});
				}else{
					window.location='index.jsp?theme='+value;	
				}
			}else if(e.target.tagName.toLowerCase() == 'img'&&target.attr('type')=='grid'){
				var gridUnit=parseInt(target.attr('value'),10);
				workspaceManager.setGridSnapConfig(gridUnit);
			}
	    });
	},
	_addGroupDom:function(data,cat,index){
		this.menuIndexs.push(index+'');
		var componentListEl=$('<div class="component-list" catkey="'+cat+'"><ul></ul></div>').appendTo(this.el.find('.data'));
		var menuSelectEl=$('<li index="'+index+'" catkey="'+cat+'">'+cat+'</li>').appendTo(this.el.find('.leftMenu ul'));
		this._addDom(data,componentListEl.find('ul'));
	},
	_addDom:function(list,el){
		var html='',type='';
		for(var i=0;i<list.length;i++){
			//if (QSPC.checkPermission(list[i].type)) {
				type=list[i].type||'';
				//html += '<li><a href="#" value="' + list[i].value + '" type="'+type+'"><img class="wstb-backgroundimage-options" src="IM/blank.gif" style="width:97px;height:69px;background-position:'+list[i].imgPosition+';" value="' + list[i].value + '" type="'+type+'"/></a><div class="info" align="center"><strong>' + list[i].info + '</strong></div></li>'
				html += '<li><a href="#" value="' + list[i].value + '" type="'+type+'"><img class="wstb-backgroundimage-options" src="IM/blank.gif" width="97" height="69" style="width:97px;height:69px;background-image:url(theme/'+QS_Theme+'/'+list[i].imgSrc+');background-position:'+list[i].imgPosition+';" value="' + list[i].value + '" type="'+type+'"/></a><div class="info" align="center"><strong>' + list[i].info + '</strong></div></li>'	
			//}
		}
		$(html).appendTo(el);
	},
	show:function(){
		this._activeMenu(0);
		this.el.show();
	},
	hide:function(){
		this.el.hide();
	},
	_activeMenu:function(index){
		var h;
		if(this.hdConfig[index].show){
			this.contentHeadEl.html(this.hdConfig[index].description).show();
			h=215;
		}else{
			this.contentHeadEl.hide();
			h=245;
		}
		this._menuSelectbyCategory(this.el.find('.leftMenu li[index="'+index+'"]'));
		this.setPanelSize(null,h);
	},
	_menuSelectbyCategory:function(target){
		var catKey=target.attr("catkey");
		target.parent().find('li').css("background","none");
		target.css("background","#646464");
		this.el.find('.bd .content div[catKey!="'+catKey+'"]').filter('.component-list').hide();
		this.el.find('.bd .content div[catKey="'+catKey+'"]').filter('.component-list').show();
	},
	setPanelSize:function(w,h){
		var parent = $(window);
        w = w||parent.width()-235;
        h = h||parent.height();
		this.el.find('.content').css('width',w);
        this.el.find('.bd .content .data').css({width:w, height:h});
        this.contentScrollPN.reSize(w,h);
	}
};

/*  
 * WorkspaceToolbar
 */
var QS_WorkspaceToolbar=function(){
	this.containerEl=null;
	this.El=null;
	this.settingEl=null;
//	this.contentEl=null;
	this.settingShow=null;
	this.contentShow=null;
	this.optionShow=null;
	this.windowsItem=null;
	this.isSaving=false;
	this.cpOption=null;
	this.ticker=null;
	this.timeOut=null;
	var qslang=QS_Lang.workspace;
	this.HTML=	'<div class="rtq-wstb">'+
				'<div class="rtq-wstb-setting"><a href="javascript:void(0)" class="qs-ui-btn rtq-wstb-setting-btn">'+qslang["tb_addwindow"]+
				'<a href="javascript:void(0)" class="qs-ui-btn rtq-wstb-setting-option">'+qslang["tb_options"]+'</a>'+
				'<div class="rtq-wstb-separator"></div>'+
				'<div class="rtq-wstb-search"><input class="qs-ui-ipt rtq-wstb-search-input" id="autocpipt_search" type="text"/>'+
				'<div class="rtq-wstb-search-cps"></div>'+
				'<a href="javascript:void(0)" class="qs-ui-btn rtq-wstb-search-button">'+qslang["tb_go"]+'</a></div>'+
				'<a href="javascript:void(0)" class="qs-ui-btn rtq-wstb-save-button">'+qslang["tb_save"]+'</a>'+
				'<div class="rtq-wstb-setting-hide">'+qslang["tb_readonly"]+'</div>'+
				'<div class="rtq-wstb-setting-date"></div>'+
				'</div>'+
				'</div>';
	// All Windows>Research>Quick take>Quote>Chart>News>Options>Time and Sales>Market Depth
	this.cpConfig=[{
		txt:qslang["tb_all"],
		val:'all'
	},QSPC.checkPermission(9)?{
		txt:qslang["tb_ddl_research"],
		val:'9'
	}:null,
	QSPC.checkPermission(3)?{	
		txt:qslang["tb_ddl_qt"],
	 	val:'3'
	}:null,
	QSPC.checkPermission(10)?{
		txt:qslang["tb_ddl_quote"],
		val:'10'
	}:null,
	QSPC.checkPermission(1)?{
		txt:qslang["tb_ddl_chart"],
		val:'1'
	}:null,
	QSPC.checkPermission(2)?{
		txt:qslang["tb_ddl_new"],
		val:'2'
	}:null,
	QSPC.checkPermission(8)?{
		txt:qslang["tb_ddl_option"],
		val:'8'
	}:null,
	QSPC.checkPermission(7)?{
		txt:qslang["tb_ddl_t&s"],
		val:'7'
	}:null,
	QSPC.checkPermission(6)?{
		txt:qslang["tb_ddl_market"],
		val:'6'
	}:null];
	this.init();
}
QS_WorkspaceToolbar.prototype={
	init:function(){
		var self=this;	
		this.containerEl=$('body');	
		this.El=$(this.HTML);	
		this.settingEl=this.El.find('.rtq-wstb-setting');
		this.dateEl=this.settingEl.find('.rtq-wstb-setting-date');
		this.btnSaveEl=this.settingEl.find('.rtq-wstb-save-button');
		//this.windowsItem=new QS_WorkspaceToolbar_WindowsItem(this,this.El);
		//this.optionsItem=new QS_WorkspaceToolbar_OptionsItem(this,this.El);
		this.El.appendTo(this.containerEl);	
		
		if(QSPC.checkPermission(9)){
			this.El.find('.rtq-wstb-search').show();
		}
		this.settingShow=(typeof Terminal.getConfig('HideToolbar')!='undefined')?(!Terminal.getConfig('HideToolbar')):true;
		this.contentShow=(typeof Terminal.getConfig('HideToolbarContent')!='undefined')?(!Terminal.getConfig('HideToolbarContent')):false;
		this._createCPOption(this.cpConfig,this.El.find('.rtq-wstb-search-cps'));
		GB_qsAutoCompleteBox.subscription("autocpipt_search",function(data,v){
			self.ticker=data;
			if(typeof(v)!="undefined"){
				$("#autocpipt_search").val(v.ticker);
			}
			self._acbAddComponent();
			//console.log(data);
		  	//workspaceManager.toolbar.autoCPCallback(data);
		},{focusClear:false,needRemember:false,secondClick:true});	
		//this.windowsItem.registerAutoComplete();
		this._initEvents();
	},
	_createCPOption:function(config,el){
		var data=[];
		for(var i=0,l=config.length;i<l;i++){
			if(config[i]!=null){
				data.push(config[i]);	
			}
		}
		var self=this;
		this.cpOption=new Util.DropDownList(el, function(t, v){
	    }, data, {
	        width: 95
	    });
	},
//	autoCPCallback:function(ticker,cpType){
//		this.windowsItem.addComponent(ticker,cpType);
//	},
	_acbAddComponent:function(){
		var self = this;
        var ticker = self.settingEl.find('.rtq-wstb-search-input').val();
        if (self.ticker != null) {
            ticker = self.ticker;
        }
        if (self.timeOut != null) {
            clearTimeout(self.timeOut);
        }
        self.timeOut = setTimeout(function(){
            if (self.cpOption.getValue() == 'all') {
                workspaceManager.addTickerToUnLockWindow(ticker);
            }else{
				if(!self.windowsItem){
		            self.windowsItem=new QS_WorkspaceToolbar_WindowsItem(self,self.El);
		            self.windowsItem.registerAutoComplete();
		        }
                self.windowsItem.addComponent(ticker, self.cpOption.getValue(), 100, 100);
            }
            self.ticker = null;
            self.settingEl.find('.rtq-wstb-search-input').val("");
        }, 200);
	},
	_initEvents:function(){
		var self=this;
		this.settingEl.bind('click',function(e){	
			var targetEl=$(e.target);
			if(targetEl.hasClass('rtq-wstb-setting-btn')){
				if(self.contentShow){
					self.hideContentBar();
				}else{
					self.showContentBar();	
				}
			}if(targetEl.hasClass('rtq-wstb-setting-option')){
				if(self.optionShow){
					if (self.optionsItem) {
						self.optionShow = false;
						self.optionsItem.hide();
					}
				}else{
					if(!self.optionsItem){
						self.optionShow=true;
						self.optionsItem=new QS_WorkspaceToolbar_OptionsItem(self,self.El);
					}
					self.optionsItem.show();
					self.hideContentBar();	
				}
			}if(targetEl.hasClass('rtq-wstb-search-button')){
				//self._acbAddComponent();
				GB_qsAutoCompleteBox.triggerACB("autocpipt_search");
				
			}if(targetEl.hasClass('rtq-wstb-save-button')&&!self.isSaving){
				if (WorkspaceTabs.currentTab.id <= -10000) {
					workspaceManager.saveAsHandler();
				}
				else {
					workspaceManager.saveWorkspace(WorkspaceTabs.currentTab, true, true);
				}
			}
			
		});	
		this.settingEl.find('.rtq-wstb-search-input').focus(function(e){
			$(this).select();
		});
	},
	setToolbarStatus:function(id){
		if(id<=-10000){
			this.showDescription();
            this.hideLastUpdateDateTime();
		}else{
			this.hideDescription();
            this.updateLastDateTime(id,false);
		}
	},
	showSettingBar:function(){	
		this.settingEl.show();
		this.settingShow=true;
		if(!Terminal.getConfig('HideToolbar')!=this.settingShow&&typeof screenShotWorkspaceID == 'undefined'){
			Terminal.setConfig({
				HideToolbar:false
			});
		}		
		WorkspaceTabs.dPanels.css("marginTop", 22);
		RtqDesktop.layout();
		workspaceManager.resizeMaxWindow();
	},
	hideSettingBar:function(isSave){
		isSave=isSave===false?false:true;
		this.settingEl.hide();
		this.hideContentBar();
		if (this.optionsItem) {
			this.optionsItem.hide();
			this.optionShow=false;
		}		
		this.settingShow=false;
		if(isSave&&!Terminal.getConfig('HideToolbar')!=this.settingShow&&typeof screenShotWorkspaceID == 'undefined'){
			Terminal.setConfig({
				HideToolbar:true
			});
		}
		WorkspaceTabs.dPanels.css("marginTop", 0);		
		RtqDesktop.layout();
		workspaceManager.resizeMaxWindow();
	},
	showContentBar:function(){
		if(!this.windowsItem){
			this.windowsItem=new QS_WorkspaceToolbar_WindowsItem(this,this.El);
			this.windowsItem.registerAutoComplete();
		}
		this.windowsItem.show();
		this.contentShow=true;
		if (this.optionsItem) {
			this.optionsItem.hide();
			this.optionShow=false;
		};		
		if(!Terminal.getConfig('HideToolbarContent')!=this.contentShow){
			Terminal.setConfig({
				HideToolbarContent:false
			});
		}	
	},
	hideContentBar:function(){
		if (this.windowsItem){
			this.windowsItem.hide();
			this.contentShow = false;
			if (!Terminal.getConfig('HideToolbarContent') != this.contentShow) {
				Terminal.setConfig({
					HideToolbarContent: true
				});
			}
		}
	},
	showDescription:function(){
		this.settingEl.find('.rtq-wstb-setting-hide').show();
	},
	hideDescription:function(){
		this.settingEl.find('.rtq-wstb-setting-hide').hide();		
	},
	showSaveLoading:function(){
		this.isSaving=true;
		this.dateEl.addClass('rtq-ddl-disable');
		this.btnSaveEl.html('Saving...').addClass('rtq-ddl-disable');
	},
	hideSaveLoading:function(){
		this.isSaving=false;
		this.dateEl.removeClass('rtq-ddl-disable');
		this.btnSaveEl.html('Save').removeClass('rtq-ddl-disable');
	},
	showLastUpdateDateTime:function(){
		this.dateEl.show();
	},
	hideLastUpdateDateTime:function(){
		this.dateEl.hide();
	},
	updateLastDateTime:function(wsID,isSaving){
		isSaving=isSaving===false?false:true;
		if (isSaving) {
			this.hideSaveLoading();
			if (wsID != WorkspaceTabs.currentTab.id) {
				return;
			}
		}
		if (gWsList[wsID].updateTime){
			this.showLastUpdateDateTime();
			this.dateEl[0].innerHTML = QS_Lang.workspace["tb_lastsave"] + this.formatDateTime(gWsList[wsID].updateTime);
		}else{
			this.hideLastUpdateDateTime();
		}
	},
	_toLocalDate:function(utcDateTime){
		var date=utcDateTime.substring(0,10);
		var arr=date.split("-");
		var year=arr[0];
		var month=parseInt(arr[1],10);
		var day=parseInt(arr[2],10);
		var time=utcDateTime.substring(10,17);
		var arr1=time.split(":");
		var hour=parseInt(arr1[0],10);
		var min=arr1[1];
		return new Date(Date.UTC(year,month-1,day,hour,min,0));
	},
	_toStringFromDate:function(date){
		var year=date.getFullYear(),
			month=date.getMonth()+1,
			day=date.getDate(),
			hour=date.getHours(),
			min=date.getMinutes();
		var str=" AM";
		if(hour>12){
			hour=hour-12;
			str=" PM";
		}else if(hour==12){
			str=" PM";
		}
		if(min<10){
			min="0"+min;
		}
		return month+"/"+day+"/"+year+", "+hour+":"+min+str;
	} ,
	formatDateTime:function(dateTime){
		return this._toStringFromDate(this._toLocalDate(dateTime));
	}
};
